import numpy as np
import pandas as pd


def entropy_weight_topsis(data):
    # 步骤1: 数据归一化
    data = np.array(data)
    # print(data)
    data = data / np.sqrt(np.sum(data**2, axis=0))
    # print(data)
    # 步骤2: 计算熵值
    p = data / data.sum(axis=0)
    k = 1.0 / np.log(len(data))
    entropy = -k * np.sum(p * np.log(p + 1e-12), axis=0)

    # 步骤3: 计算权重
    d = 1 - entropy
    w = d / d.sum()
    print(w)
    # 步骤4: 计算加权归一化矩阵
    weighted_data = data * w

    # 步骤5: 确定理想解和负理想解
    ideal_solution = weighted_data.max(axis=0)
    negative_ideal_solution = weighted_data.min(axis=0)

    # 步骤6: 计算到理想解和负理想解的距离
    distance_to_ideal = np.sqrt(((weighted_data - ideal_solution) ** 2).sum(axis=1))
    distance_to_negative_ideal = np.sqrt(
        ((weighted_data - negative_ideal_solution) ** 2).sum(axis=1)
    )

    # 步骤7: 计算TOPSIS得分
    topsis_score = distance_to_negative_ideal / (
        distance_to_ideal + distance_to_negative_ideal
    )

    return topsis_score


if __name__ == "__main__":
    df = pd.read_csv("data/combined_importance2.csv")
    df.fillna(0.0, inplace=True)
    data_without_feature_names = df.iloc[:, 1:]
    scores = entropy_weight_topsis(data_without_feature_names)
    df["TOPSIS_Score"] = scores
    df_sorted = df.sort_values(by="TOPSIS_Score", ascending=False)
    # df_sorted.to_csv("data/topsis_result.csv", index=False)
    features_list = df_sorted["Feature"][:20].tolist()  # 转换为列表
    print(features_list)  # 打印为列表形式
